//
//  DatePickerTableView.swift
//  UI Single
//
//  Created by vivi on 6/3/16.
//  Copyright © 2016 vivi. All rights reserved.
//

import UIKit

protocol DatePickerTableViewDelegate: class {
    func datePickerTableViewDidSelectNew(datePickerTableView: DatePickerTableView)
}

class DatePickerTableView: UITableView, UITableViewDataSource, UITableViewDelegate {
    
    var texts = [String]() {
        didSet {
            self.reloadData()
        }
    }
    var maxNumToShow = -1 //如果小于0，那么全部显示，如果设置成一个大于0的数目，那么只显示maxNumToShow个
    {
        didSet {
            self.reloadData()
        }
    }
    
    weak var datePickerDelegate: DatePickerTableViewDelegate? //为了避免名字重复
    
    var currentText: String {
        get {
            return (self.visibleCells[self.visibleCells.count >> 1] as! DatePickerTableViewCell).title
        }
        set {
            setCurrentTextTo(newValue, animated: false)
        }
    }
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        configureInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureInit()
    }
    
    init(frame: CGRect) {
        super.init(frame: frame, style: .Plain)
        configureInit()
    }
    
    func configureInit() {
        self.tableHeaderView = nil
        self.tableFooterView = nil
        
        self.dataSource = self
        self.delegate = self 
        
        self.bounces = false
        
        self.separatorStyle = .None
        self.showsVerticalScrollIndicator = false
        self.showsHorizontalScrollIndicator = false
        
        let nib = UINib.init(nibName: "DatePickerTableViewCell", bundle: nil)
        self.registerNib(nib, forCellReuseIdentifier: "DatePickerTableViewCell")
    }
    
    func setCurrentTextTo(currentText: String, animated: Bool) {
        for (i, text) in texts.enumerate() {
            if (text == currentText && (maxNumToShow < 0 || i < maxNumToShow)) {
                //在这里设置成i的原因是居中显示的是第i+2个，前面两个是空格，但是我们设置的是最顶部的，因此成了i
                self.scrollToRowAtIndexPath(NSIndexPath.init(forRow: i, inSection: 0), atScrollPosition: .Top, animated: animated)
                return;
            }
        }
    }
    
    //MARK: - UITableView Datasource 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func numberOfTextToShow() -> Int {
        if maxNumToShow < 0  {
            return self.texts.count
        }
        else {
            return maxNumToShow
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return numberOfTextToShow() + 6 //4 = 2 + 2分别为了最上面和最下面能够滑到中间
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("DatePickerTableViewCell") as! DatePickerTableViewCell
        let n = numberOfTextToShow()
        var textIdx = (indexPath.row - 3) % n
        if textIdx < 0 {
            textIdx += n;
        }
        cell.title = texts[textIdx]
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.frame.height / 5.0
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let n = CGFloat(numberOfTextToShow())
        let x = self.frame.height / 5.0
        
        let bottomOffset = self.contentSize.height - self.frame.height
        if self.contentOffset.y >= bottomOffset {
            self.setContentOffset(CGPointMake(self.contentOffset.x, self.contentOffset.y - n * x), animated: false)
        }
        else if (self.contentOffset.y <= 0.0) {
            self.setContentOffset(CGPointMake(self.contentOffset.x, self.contentOffset.y + n * x), animated: false)

        }
        
        datePickerDelegate?.datePickerTableViewDidSelectNew(self)
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        if let indexPath = self.indexPathsForVisibleRows?.first {
            self.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
            //datePickerDelegate?.datePickerTableViewDidSelectNew(self)
        }
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if let indexPath = self.indexPathsForVisibleRows?.first {
            self.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
            //datePickerDelegate?.datePickerTableViewDidSelectNew(self)
        }
    }
}
